<template>
  <Row>
    <Col span="13">
      <Form :model="formItem" :label-width="120" ref="formItem" :rules="add_ruleValidate">
        <Card>
          <Card style="margin-top:-15px">
            <p slot="title">
              微信模板编辑
              <a href="#" slot="extra" @click.prevent="returnTable()" style="float:right">
                <Icon type="arrow-left-c"></Icon>返回
              </a>
            </p>
            <p>
              <Form-item label="模板名称" required prop="name">
                <Input v-model="formItem.name" placeholder="请输入限100个字,本系统中定义的名称"></Input>
              </Form-item>

              <Form-item label="模板编码" required prop="code">
                <Input v-model="formItem.code" placeholder="请输入"></Input>
              </Form-item>

              <Form-item label="微信公众号" required prop="appId">
                <Select v-model="formItem.appId" placeholder="请选择公众号" @on-change="checkAppId(formItem.appId)" clearable>
                  <Option v-for="(app, index) in appIds" :key="app.authorizerAppid" :value="app.authorizerAppid">{{app.nickName}}</Option>
                </Select>
              </Form-item>

              <Form-item label="微信模板" required prop="tempId">
                <Select v-model="formItem.templateId" placeholder="请选择微信模板"
                  @on-change="checkTemplateId(formItem.templateId)"
                  clearable>
                  <Option v-for="(template, index) in templates" :key="template.id" :value="template.id">{{template.title}}</Option>
                </Select>
              </Form-item>

              <FormItem label="URL">
                <Input v-model="formItem.linkUrl" type="textarea" id="myinput" width="450" :autosize="{minRows: 3,maxRows: 8}"></Input>
              </FormItem>
            </p>
          </Card>
          <Card style="margin-top:10px">
            <p slot="title">模板内容</p>
            <p>
                <template v-for="(content, contentsIndex) in formItem.contents">
                  <Row> 
                    <Col span="10" style="width:70%;">
                      <Form-item :label="content.label" prop="value"  style="width:100%;">

                        <Select v-model="content.fieldValue" multiple filterable style="width:260px">
                          <Option v-for="item in formItem.fieldlist" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                      </Form-item>
                    </Col>
                    <Col span="6" push="6" style="z-index:10000;">
                      <colorPicker  v-model="content.color"/>
                    </Col>
                  </Row>
                </template>
              <Button size="large" type="primary" long  @click="editInfo('formItem')" :loading="loading">保存</Button>
            </p>
          </Card>
        </Card>
      </Form>
    </Col>

    <Col span="10" push="1">
      <Card>
        <p slot="title">参数样例</p>
        <p>
          <Card style="margin-top:10px">
            <p slot="title">模板名称: {{formItem.name}}</p>
          </Card>
          <Card style="margin-top:10px">
            <p slot="title">内容:</p>
            <p v-for="(content,index) in formItem.contents" :key="index">
              <span style="font-weight: 800;margin-bottom:5px">{{content.label}}</span>
              <span :style="{color: content.color}">{{content.value}}</span>
            </p>
          </Card>
          <Card style="margin-top:10px">
            <p slot="title">内容示例:</p>
            <pre>{{formItem.example}}</pre>
          </Card>
        </p>
      </Card>
    </Col>
  </Row>
</template>
<script>
import vcolorpicker from "vcolorpicker";
import {
  fetchAppId,
  fetchTemplateDetail,
  fetchTemplates,
  addTemplates,
  fetchTempById,
  editTemplates
} from "@/api/wx";
import { fetchdynamicfield } from "@/api/marketing";
import { setTimeout } from 'timers';
export default {
  name: "list",
  components: {},
  data() {
    return {
      model13: '',
      formItem: {
        contents: [],
        fieldlist:[], // 短信动态字段列表
      },
      add_ruleValidate: {
        name: [
          {
            required: true,
            message: "请输入模板名称",
            trigger: "blur"
          },
          {
            type: "string",
            max: 12,
            message: "模板名称长度不能大于100个字",
            trigger: "blur"
          }
        ],

        code: [
          {
            required: true,
            message: "请输入模板编码",
            trigger: "blur"
          }
        ],
        appId: [
          {
            required: true,
            message: "请选择公众号",
            trigger: "change"
          }
        ],

        tempId: [
          {
            required: false,
            message: "请选择微信模板",
            trigger: "change"
          }
        ]
      },
      appIds: [],
      templates: [],
      templateDetail: {},
      loading: false,
      communicationField : [],
    };
  },

  methods: {
    editInfo(name) {
      var _self = this;
      this.loading = true;

      this.$refs[name].validate(valid => {
        if (valid) {
          var params = this.formItem;
          let communicationFields = [];
          params.contents.forEach(item =>{
            communicationFields = communicationFields.concat(item.fieldValue);
          });
          params.communicationFields = communicationFields;
          editTemplates(params).then(res => {
              if (res.data.code == 0) {
                this.$Message.info("保存成功！");
                setTimeout(()=>{
                    this.$router.push({path:'/campaign/wxtemplate'});
                },1500)
              }
            })
            .catch(error => {
              this.$Message.error(error);
            });
        } else {
          this.$Message.error("表单验证失败!");
          this.loading = false;
        }
      });
    },    
    
    returnTable() {
      this.$router.back(-1);
    },

    //选择公众号后---
    checkAppId(appId) {
      var params = {
        appId: appId
      };
      fetchTemplates(params)
        .then(res => {
          if (res.data.code == 0) {
            this.templates = res.data.data;
            this.DateReady = true;
          }
        })
        .catch(error => {
          this.$Message.error(error);
        });
    },
    //选择模板ID后---
    checkTemplateId(id) {
      var params = {
        id: id
      };
      fetchTemplateDetail(params).then(res => {
          if (res.data.code == 0) {
            var resbody = res.data.data;
            for (var i = 0; i < resbody.contentSet.length; i++) {
              resbody.contentSet[i].color = "#000000";
              resbody.contentSet[i].loading2 = false;
              resbody.contentSet[i].fieldValue = [];
            }
            this.formItem.contents = resbody.contentSet;
            this.formItem.example = resbody.example;
            this.formItem.deputyIndustry = resbody.deputyIndustry;
            this.formItem.primaryIndustry = resbody.primaryIndustry;
            this.formItem.title = resbody.title;
          }
        })
        .catch(error => {
          this.$Message.error(error);
        });

    },

    Fetchdynamicfield(params){     // 查询短信模板动态字段
     var reqParams = {
       limit:10,
       page:1
     }
      fetchdynamicfield(reqParams).then((res)=>{
        this.loading1 = true;
        if(res.status == 200){
          this.loading1 = false;
          let obj = res.data.records;
          let str = '';
          let arr = [];
          this.communicationField = obj;
          obj.forEach(item=>{
            str = item.label;
            var field = {
              'label': item.label,
              'value': item.id
            };
            arr.push(field) ;
            this.formItem.fieldlist = arr;
          })
          for(var i = 0;i < res.data.records.length;i++){
              this.formItem.classlist = res.data.records[i].code;
          };

        }
      })
      .catch((error)=>{
         this.$Message.error("操作失败【" + error + "】");
      })
    },

    loadData(){
      fetchAppId().then(res => {
        if (res.data.code == 0) {
          this.appIds = res.data.data;
          this.DateReady = true;
        }
      })
        .catch(error => {
          this.$Message.error(error);
        });

      var params = {
        id: this.$route.query._id
      };
      fetchTempById(params).then(res => {
        if (res.data.code == 0) {
          this.checkAppId(res.data.data.appId);
          this.formItem = res.data.data;
          this.formItem.contents = JSON.parse(res.data.data.contents);
        }
      })
        .catch(error => {
          this.$Message.error(error);
        });
    }
  },

  created() {

  },
  mounted () {
    this.Fetchdynamicfield();
    this.loadData();
  }
};
</script>
<style lang="scss" scoped>

</style>

